<template>
  <ContentWrap>
    <!-- 搜索栏：仅在无userId时显示 -->
    <el-form
v-if="!props.userId" class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true"
      label-width="68px">
      <el-form-item label="年份" prop="years">
        <el-input
v-model="queryParams.years" placeholder="请输入年份" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="假期类型" prop="leaveType">
        <el-select v-model="queryParams.leaveType" placeholder="请选择假期类型" clearable class="!w-240px">
          <el-option v-for="item in holidayTypeList" :key="item.id" :label="item.leaveName" :value="item.leaveType" />
        </el-select>
      </el-form-item>
      <el-form-item label="员工姓名" prop="userName">
        <el-input
v-model="queryParams.userName" placeholder="请输入员工姓名" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
v-model="queryParams.createTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['oa:employee-leave-balance:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <!-- <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['oa:employee-leave-balance:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
      </el-form-item>
    </el-form>
    <!-- 新增按钮：子表模式下单独展示 -->
    <el-button v-else type="primary" @click="openForm('create')" style="margin-bottom: 10px;">新增假期</el-button>
    <!-- 合同期内假期余额批量生成按钮，仅在作为员工档案子表组件时显示 -->
    <el-button
v-if="props.userId" type="success" style="margin-bottom: 10px; margin-left: 10px;"
      @click="handleGenerateLeaveBalance" v-hasPermi="['oa:employee-leave-balance:create']">
      批量生成假期余额
    </el-button>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!-- <el-table-column label="序号" align="center" prop="id" /> -->
      <el-table-column label="年份" align="center" prop="years" />
      <el-table-column label="员工姓名" align="center" prop="userName" />
      <!-- <el-table-column label="假期编码" align="center" prop="leaveType" /> -->
      <el-table-column label="假期名称" align="center" prop="leaveName" />
      <el-table-column label="标准数" align="center" prop="standardDays">
        <template #default="scope">
          <span>{{ scope.row.standardDays }} {{ scope.row.leaveName === '调休' ? '小时' : '天' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="剩余结余" align="center" prop="remaining">
        <template #default="scope">
          <span>{{ scope.row.remaining }} {{ scope.row.leaveName === '调休' ? '小时' : '天' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
link type="primary" @click="openForm('update', scope.row.id)"
            v-hasPermi="['oa:employee-leave-balance:update','oa:employee-archive:update']">
            编辑
          </el-button>
          <el-button
link type="danger" @click="handleDelete(scope.row.id)"
            v-hasPermi="['oa:employee-leave-balance:delete','oa:employee-archive:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页：仅在无userId时显示 -->
    <Pagination
v-if="!props.userId" :total="total" v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <EmployeeLeaveBalanceForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { EmployeeLeaveBalanceApi, EmployeeLeaveBalanceVO } from '@/api/oa/employeeleavebalance'
import EmployeeLeaveBalanceForm from './EmployeeLeaveBalanceForm.vue'
import { defineProps, watch } from 'vue'
import { generateEmployeeLeaveBalance } from '@/api/oa/employeeleavebalance'

/** 支持作为子表嵌入：接收 userId 和 userName 作为 prop */
const props = defineProps<{ userId?: number, userName?: string, years?: number, hireDate?: number, endDate?: number }>()

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EmployeeLeaveBalanceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  years: undefined as number | undefined,
  leaveType: undefined,
  userName: undefined,
  userId: props.userId,
  createTime: []
})
let holidayTypeList = ref() // 假期类型
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 如果有userId，仅查该员工数据
    if (props.userId) {
      queryParams.userId = props.userId
      queryParams.pageNo = 1
      queryParams.pageSize = 100 // 子表模式下不分页
    }
    const data = await EmployeeLeaveBalanceApi.getEmployeeLeaveBalancePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const getHolidayStandardsPage = async () => {
  try {
    const params = queryParams
    params.pageSize = 100
    const data = await EmployeeLeaveBalanceApi.getHolidayStandardsPage(params)
    holidayTypeList = data.list
  } finally {

  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 监听 userId 变化自动刷新 */
watch([() => props.userId, () => props.years], ([userId, years]) => {
  if (userId) {
    queryParams.userId = userId
    if (years) queryParams.years = years
    getList()
  }
}, { immediate: true })

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  // 子表模式下，新增时传递 userId、userName、years
  if (type === 'create' && props.userId) {
    formRef.value.open(type, undefined, props.userId, props.userName, props.years)
  } else {
    formRef.value.open(type, id)
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await EmployeeLeaveBalanceApi.deleteEmployeeLeaveBalance(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await EmployeeLeaveBalanceApi.exportEmployeeLeaveBalance(queryParams)
    download.excel(data, '员工假期余额管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 合同期内假期余额批量生成按钮操作 */
const handleGenerateLeaveBalance = async () => {
  if (props.hireDate == null || props.endDate == null) {
    message.warning('请先完善入职日期和结束日期')
    return
  }
  if (!props.userId || !props.userName) {
    message.warning('员工信息不完整')
    return
  }
  try {
    await generateEmployeeLeaveBalance({
      userId: props.userId,
      userName: props.userName,
      hireDate: props.hireDate,
      endDate: props.endDate
    })
    message.success('假期余额生成成功')
    getList()
  } catch (e) {
    // 若依message已自动处理异常
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getHolidayStandardsPage()
})
</script>
